package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.exception.QwMsg;
import com.zhangtai.modules.constVo.NoticeConst;
import com.zhangtai.modules.constVo.ScoreConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
import com.zhangtai.modules.dto.*;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.score.*;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.sroce.*;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import com.zhangtai.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("score")
@Api(tags = "360评分")
@Slf4j
public class ScoreController {
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private ScoreDao scoreDao;
    @Autowired
    private LoginController loginController;
    @Autowired
    private JobController jobController;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private ScoreRaterService scoreRaterService;
    @Autowired
    private ScoreRaterDao scoreRaterDao;
    @Autowired
    private ScoreWeightsService scoreWeightsService;
    @Autowired
    private ScoreWeightsDao scoreWeightsDao;
    @Autowired
    private ScoreProgramService scoreProgramService;
    @Autowired
    private ScoreProgramDao scoreProgramDao;
    @Autowired
    private ScoreProgramTopicDao scoreProgramTopicDao;
    @Autowired
    private ScoreTopicDao scoreTopicDao;
    @Autowired
    private ScoreTopicService scoreTopicService;
    @Autowired
    private QwMsg qwMsg;
//    @Autowired
//    private JobDaoMssql jobDaoMssql;

    @GetMapping("/getScorePage")
    @ApiOperation(value = "查询360评分")
    public R getScorePage(@RequestParam(value = "serialNumber",required = false) String serialNumber,
                          @RequestParam(value = "status",required = false) List<Integer> status,
                          @RequestParam(value = "name",required = false) String name,
                          @RequestParam(value = "code",required = false) String code,
                          @RequestParam(value = "programId",required = false) String programId,
                          @RequestParam(value = "orgName",required = false) String orgName,
                          @RequestParam(value = "unitName",required = false) String unitName,
                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                          HttpServletRequest request
    ) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> selectOrg = null;
        List<Long> selectUnit = null;
        //null未查询，size为0查询结果为空
        if(!org.springframework.util.StringUtils.isEmpty(orgName)){
//            selectOrg = jobDaoMssql.findOrgByName(orgName);
            if(selectOrg==null){
                selectOrg = new ArrayList<>();
            }
        }
        if(!org.springframework.util.StringUtils.isEmpty(unitName)){
//            selectUnit = jobDaoMssql.findOrgByName(unitName);
            if(selectUnit==null){
                selectUnit = new ArrayList<>();
            }
        }
        Page<ScoreDto> page = new Page<ScoreDto>(pageNum,pageSize);
        List<ScoreDto> scoreDtoList=  scoreDao.getScorePage(orgIds,serialNumber,status,programId,selectOrg,selectUnit,name,code,page);
        for (ScoreDto scoreDto:scoreDtoList){
            if(scoreDto.getJobId()!=null) scoreDto.setJobName(jobController.getJobName(scoreDto.getJobId()));
            if(scoreDto.getOrgId()!=null) scoreDto.setOrgName(jobController.getOrgNameById(scoreDto.getOrgId()));
            if(scoreDto.getUnitId()!=null) scoreDto.setUnitName(jobController.getOrgNameById(scoreDto.getUnitId()));
        }
        page.setRecords(scoreDtoList);
        return R.ok(new PageResult<ScoreDto>(page));
    }

    @GetMapping("/getScoreTopicPage")
    @ApiOperation(value = "分页查询360题目列表")
    public R getScoreTopicPage(@RequestParam(value = "title",required = false) String title,
                               @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize ) throws Exception {

        PageResult result= scoreTopicService.queryPage(title,pageNum,pageSize);

        return R.ok(result);
    }
    @GetMapping("/getScoreTopicList")
    @ApiOperation(value = "全部查询360题目")
    public R getScoreTopicList() throws Exception {
        List<ScoreTopicEntity> scoreTopicEntityList= scoreTopicDao.selectList(new QueryWrapper<ScoreTopicEntity>().eq("is_delete",0));
        return R.ok(scoreTopicEntityList);
    }

    @GetMapping("/getScoreProgramAndTopic")
    @ApiOperation(value = "根据360方案id查询关联的题目id")
    public R getScoreProgramAndTopic(@RequestParam(value = "id") String id) throws Exception {
        List<ScoreProgramTopicEntity> scoreProgramTopicEntityList= scoreProgramTopicDao.selectList(new QueryWrapper<ScoreProgramTopicEntity>()
                .eq("is_delete",0).eq("program_id", id));
        return R.ok(scoreProgramTopicEntityList);
    }


    @GetMapping("/getSoreTopicScore")
    @ApiOperation("获取360评价题目提交的分数")
    public R getSoreTopicScore(@RequestParam(value = "id") String id){
        ScoreRaterEntity scoreRaterEntity= scoreRaterService.getByIdE(Long.valueOf(id));
        List<ScoreTopicScoreDto> scoreTopicScoreDtoList= JSONObject.parseArray(scoreRaterEntity.getScoreArray(), ScoreTopicScoreDto.class);
        return R.ok(scoreTopicScoreDtoList);
    }

    @PostMapping("/saveSoreProgramTopic")
    @ApiOperation("保存360方案和题目关联表")
    public R saveSoreProgramTopic(@RequestBody @Valid ScoreProgramTopicListVo scoreProgramTopicListVo){

        if(CollectionUtils.isEmpty(scoreProgramTopicListVo.getScoreProgramTopicVoArrayList())){
            return R.ok();
        }
        for (ScoreProgramTopicVo scoreProgramTopicVo:scoreProgramTopicListVo.getScoreProgramTopicVoArrayList()){
            ScoreProgramTopicEntity scoreProgramTopicEntity = BeanUtilsMabach.doToDto(scoreProgramTopicVo, ScoreProgramTopicEntity.class);
            scoreProgramTopicEntity.setIsDelete(0);
            scoreProgramTopicDao.insert(scoreProgramTopicEntity);
        }
        return R.ok();
    }



    @PostMapping ("/saveAndUpdateScore")
    @ApiOperation(value = "保存或修改360评分")
    @SysAuthorityLog(value = "保存或修改360评分")
    @Transactional
    public R saveAndUpdateScore(@RequestBody @Valid ScoreVo scoreVo, HttpServletRequest request) throws Exception {

        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        ScoreEntity scoreEntity = BeanUtilsMabach.doToDto(scoreVo, ScoreEntity.class);
        EmployeeInfoEntity employeeInfoEntity=employeeInfoService.getByIdE(scoreVo.getOid());
        scoreEntity.setName(employeeInfoEntity.getName());
        scoreEntity.setJobId(employeeInfoEntity.getJobId());
        scoreEntity.setOrgId(employeeInfoEntity.getOrgId());
        scoreEntity.setUnitId(employeeInfoEntity.getUnitId());
        Integer sum=0;
        Integer superiorSum= CollectionUtils.isEmpty(scoreVo.getSuperiorList())?0:scoreVo.getSuperiorList().size();
        Integer sameLeveSum= CollectionUtils.isEmpty(scoreVo.getSameLevelList())?0:scoreVo.getSameLevelList().size();
        Integer subordinateSum= CollectionUtils.isEmpty(scoreVo.getSubordinateList())?0:scoreVo.getSubordinateList().size();
        sum=superiorSum+sameLeveSum+subordinateSum;
        if(1==scoreVo.getIsAppraisal()) sum++;
        scoreEntity.setSum(sum);

        if(scoreVo.getId()==null){
            scoreEntity.setSerialNumber(getScoreNum());
            scoreEntity.setCreateTime(new Date());
            scoreEntity.setInsetDate(new Date());
            scoreEntity.setCreateCode(userInfo.getString("usercode"));
            scoreEntity.setCreateName(userInfo.getString("name"));
            scoreEntity.setStatus(0);
            scoreDao.insert(scoreEntity);
        }else {
            scoreRaterDao.delete(new QueryWrapper<ScoreRaterEntity>().eq("score_id",scoreVo.getId()));
            scoreService.updateByIdE(scoreEntity);
        }
        ScoreProgramEntity scoreProgramEntity=  scoreProgramService.getByIdE(scoreEntity.getProgramId());
        if(!CollectionUtils.isEmpty(scoreVo.getSuperiorList())){
            saveScoreRater(scoreEntity.getId(),userInfo,scoreVo.getSuperiorList(), ScoreConst.SCORE_SUPERIOR_EIGHTS_TYPE,scoreProgramEntity.getWeightsId());
        }
        if(!CollectionUtils.isEmpty(scoreVo.getSameLevelList())){
            saveScoreRater(scoreEntity.getId(),userInfo,scoreVo.getSameLevelList(), ScoreConst.SCORE_SAME_LEVEL_EIGHTS_TYPE,scoreProgramEntity.getWeightsId());
        }
        if(!CollectionUtils.isEmpty(scoreVo.getSubordinateList())){
            saveScoreRater(scoreEntity.getId(),userInfo,scoreVo.getSubordinateList(), ScoreConst.SCORE_SUBORDINATE_EIGHTS_TYPE,scoreProgramEntity.getWeightsId());
        }
        if(1==scoreVo.getIsAppraisal()){
            ArrayList<String> list=new ArrayList();
            list.add(scoreVo.getOid().toString());
            saveScoreRater(scoreEntity.getId(),userInfo,list, ScoreConst.SCORE_MY_EIGHTS_TYPE,scoreProgramEntity.getWeightsId());
        }
        scoreProgramEntity.setIsEnable(1);
        scoreProgramService.updateByIdE(scoreProgramEntity);
        return R.ok();
    }
    @GetMapping("getScoreUpdateDetail")
    @ApiOperation(value = "获取360评价修改信息详情")
    public R getScoreUpdateDetail(@RequestParam(value = "id") String id){
        ScoreEntity scoreEntity=  scoreService.getByIdE(Long.valueOf(id));
        ScoreUpdateDetailDto scoreUpdateDetailDto = BeanUtilsMabach.doToDto(scoreEntity, ScoreUpdateDetailDto.class);
        if(scoreUpdateDetailDto.getJobId()!=null) scoreUpdateDetailDto.setJobName(jobController.getJobName(scoreUpdateDetailDto.getJobId()));
        if(scoreUpdateDetailDto.getOrgId()!=null) scoreUpdateDetailDto.setOrgName(jobController.getOrgNameById(scoreUpdateDetailDto.getOrgId()));
        if(scoreUpdateDetailDto.getUnitId()!=null) scoreUpdateDetailDto.setUnitName(jobController.getOrgNameById(scoreUpdateDetailDto.getUnitId()));
        List<ScoreRaterEntity> scoreRaterEntityList=scoreRaterDao.selectList(new QueryWrapper<ScoreRaterEntity>().eq("score_id",scoreEntity.getId()).eq("is_delete",0));
        JSONArray superiorList=new JSONArray();
        JSONArray sameLevelList=new JSONArray();
        JSONArray subordinateList=new JSONArray();
        for (ScoreRaterEntity scoreRaterEntity:scoreRaterEntityList){
            JSONObject object=new JSONObject();
            object.put("oid", scoreRaterEntity.getOid().toString());
            object.put("name", scoreRaterEntity.getName());
            object.put("unitId", scoreRaterEntity.getUnitId());
            if(ScoreConst.SCORE_SUPERIOR_EIGHTS_TYPE==scoreRaterEntity.getType()){
                superiorList.add(object);
            }
            if(ScoreConst.SCORE_SAME_LEVEL_EIGHTS_TYPE==scoreRaterEntity.getType()){
                sameLevelList.add(object);
            }
            if(ScoreConst.SCORE_SUBORDINATE_EIGHTS_TYPE==scoreRaterEntity.getType()){
                subordinateList.add(object);
            }
        }
        scoreUpdateDetailDto.setSuperiorList(superiorList);
        scoreUpdateDetailDto.setSameLevelList(sameLevelList);
        scoreUpdateDetailDto.setSubordinateList(subordinateList);
        return   R.ok(scoreUpdateDetailDto);
    }

    @GetMapping("updateScoreStop")
    @ApiOperation(value = "360评价终止")
    @Transactional
    public R updateScoreStop(@RequestParam(value = "id") String id){
        ScoreEntity scoreEntity=  scoreService.getByIdE(Long.valueOf(id));
        ScoreProgramEntity scoreProgramEntity=  scoreProgramService.getByIdE(scoreEntity.getProgramId());
        scoreEntity.setStatus(3);
        BigDecimal score=new BigDecimal(0);
        BigDecimal weights=new BigDecimal(0);

        ScoreWeightsEntity scoreWeightsEntity=scoreWeightsService.getByIdE(scoreProgramEntity.getWeightsId());
        List<ScoreRaterEntity> scoreRaterNoScore=scoreRaterDao.selectList(new QueryWrapper<ScoreRaterEntity>()
                .eq("score_id",scoreEntity.getId())
                .eq("is_delete",0).eq("status",0));
        for(ScoreRaterEntity scoreRaterEntity:scoreRaterNoScore){
            scoreRaterEntity.setStatus(2);
            scoreRaterService.updateByIdE(scoreRaterEntity);
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("score",score);
        jsonObject.put("weights",weights);

        jsonObject= getScore(jsonObject,scoreEntity.getId(),scoreWeightsEntity.getSuperiorWeights(), ScoreConst.SCORE_SUPERIOR_EIGHTS_TYPE);
        jsonObject= getScore(jsonObject,scoreEntity.getId(),scoreWeightsEntity.getSameLevelWeights(), ScoreConst.SCORE_SAME_LEVEL_EIGHTS_TYPE);
        jsonObject= getScore(jsonObject,scoreEntity.getId(),scoreWeightsEntity.getSubordinateWeights(), ScoreConst.SCORE_SUBORDINATE_EIGHTS_TYPE);
        jsonObject= getScore(jsonObject,scoreEntity.getId(),scoreWeightsEntity.getMyWeights(), ScoreConst.SCORE_MY_EIGHTS_TYPE);

        score=jsonObject.getBigDecimal("score");
        weights=jsonObject.getBigDecimal("weights");
        scoreEntity.setScore(weights.compareTo(BigDecimal.ZERO)==0?new BigDecimal("0"):score.divide(weights, 2, BigDecimal.ROUND_HALF_UP));
        return scoreService.updateByIdE(scoreEntity);
    }



    @GetMapping("getSelectProgram")
    @ApiOperation(value = "获取评价类型选项")
    public R getSelectProgram(){
        //List<ScoreProgramEntity> scoreProgramEntityList=scoreProgramDao.selectList(new QueryWrapper<ScoreProgramEntity>().eq("is_delete",0));
        Page<ScoreProgramDto> page = new Page<ScoreProgramDto>(1,200);
        List<ScoreProgramDto> scoreProgramDtoList=  scoreProgramDao.getScoreProgramPage(page);
        return R.ok(scoreProgramDtoList);
    }
    @GetMapping("getScoreProgramPage")
    @ApiOperation(value = "分页获取评价类型信息")
    public R getScoreProgramPage( @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){

        Page<ScoreProgramDto> page = new Page<ScoreProgramDto>(pageNum,pageSize);
        List<ScoreProgramDto> scoreProgramDtoList=  scoreProgramDao.getScoreProgramPage(page);
        page.setRecords(scoreProgramDtoList);
        return R.ok(new PageResult<ScoreProgramDto>(page));
    }


    @GetMapping("getScoreInfo")
    @ApiOperation(value = "获取360评价详情")
    public R getScoreInfo(@RequestParam(value = "id") String id,HttpServletRequest request) throws Exception {

        JSONObject userInfo = loginController.getUserInfo(request).getData();

        ScoreEntity scoreEntity    =   scoreService.getByIdE(Long.valueOf(id));
        ScoreProgramEntity scoreProgramEntity=  scoreProgramService.getByIdE(scoreEntity.getProgramId());
        EmployeeInfoEntity employeeInfoEntity=  employeeInfoService.getByIdE(scoreEntity.getOid());
        ScoreInfoDto scoreInfoDto = BeanUtilsMabach.doToDto(scoreEntity, ScoreInfoDto.class);
        if(scoreInfoDto.getJobId()!=null) scoreInfoDto.setJobName(jobController.getJobName(scoreInfoDto.getJobId()));
        if(scoreInfoDto.getOrgId()!=null) scoreInfoDto.setOrgName(jobController.getOrgNameById(scoreInfoDto.getOrgId()));
        if(scoreInfoDto.getUnitId()!=null) scoreInfoDto.setUnitName(jobController.getOrgNameById(scoreInfoDto.getUnitId()));
        scoreInfoDto.setProgramName(scoreProgramEntity.getProgramName());
        scoreInfoDto.setCode(employeeInfoEntity.getCode());
        List<ScoreTopicDto> scoreTopicDtoList= scoreProgramTopicDao.getScoreTopic(scoreEntity.getProgramId());
        ScoreWeightsEntity scoreWeightsEntity=scoreWeightsService.getByIdE(scoreProgramEntity.getWeightsId());
        List<ScoreRaterEntity> scoreRaterEntityList=scoreRaterDao.selectList(new QueryWrapper<ScoreRaterEntity>().eq("score_id",scoreEntity.getId()).eq("is_delete",0));
        Map<Long,List<ScoreTopicScoreDto>> map=new HashMap();
        for(ScoreRaterEntity scoreRaterEntity:scoreRaterEntityList){
            if(StringUtils.isEmpty(scoreRaterEntity.getScoreArray())){
                continue;
            }
            List<ScoreTopicScoreDto> scoreTopicScoreDtoList= JSONObject.parseArray(scoreRaterEntity.getScoreArray(), ScoreTopicScoreDto.class);
            for (ScoreTopicScoreDto scoreTopicScoreDto:scoreTopicScoreDtoList){
                scoreTopicScoreDto.setType(scoreRaterEntity.getType());
                List<ScoreTopicScoreDto> scoreTopicScoreDtos;
                if(map.get(scoreTopicScoreDto.getId())==null){
                    scoreTopicScoreDtos=new ArrayList<>();
                }else{
                    scoreTopicScoreDtos=map.get(scoreTopicScoreDto.getId());
                }
                scoreTopicScoreDtos.add(scoreTopicScoreDto);
                map.put(scoreTopicScoreDto.getId(),scoreTopicScoreDtos);
            }
        }
        for (ScoreTopicDto scoreTopicDto:scoreTopicDtoList){
            List<ScoreTopicScoreDto> scoreTopicScoreDtos=map.get(scoreTopicDto.getId());
            BigDecimal score=new BigDecimal(0);
            BigDecimal weights=new BigDecimal(0);
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("score",score);
            jsonObject.put("weights",weights);
            if(!CollectionUtils.isEmpty(scoreTopicScoreDtos)) {
                jsonObject = getRaterTopicScore( jsonObject, scoreTopicScoreDtos, ScoreConst.SCORE_SUPERIOR_EIGHTS_TYPE, scoreWeightsEntity.getSuperiorWeights());
                jsonObject = getRaterTopicScore(jsonObject,  scoreTopicScoreDtos, ScoreConst.SCORE_SAME_LEVEL_EIGHTS_TYPE, scoreWeightsEntity.getSameLevelWeights());
                jsonObject = getRaterTopicScore(jsonObject, scoreTopicScoreDtos, ScoreConst.SCORE_SUBORDINATE_EIGHTS_TYPE, scoreWeightsEntity.getSubordinateWeights());
                jsonObject = getRaterTopicScore(jsonObject,  scoreTopicScoreDtos, ScoreConst.SCORE_MY_EIGHTS_TYPE, scoreWeightsEntity.getMyWeights());
            }
            score=jsonObject.getBigDecimal("score");
            weights=jsonObject.getBigDecimal("weights");
            scoreTopicDto.setAverageScore( weights.compareTo(BigDecimal.ZERO)==0?new BigDecimal("0"):score.divide(weights, 2, BigDecimal.ROUND_HALF_UP));
        }
        scoreInfoDto.setScoreTopicDtoList(scoreTopicDtoList);
        //  校验是否有查看 360评分分数权限
        JSONArray authorities = userInfo.getJSONArray("authorities");
        List<String> list = JSON.parseObject(authorities.toJSONString(), List.class);
        if (!list.contains("score:raterScore:get")){
            for (ScoreRaterEntity scoreRaterEntity:scoreRaterEntityList){
                scoreRaterEntity.setRaterScore(null);
            }
        }
        scoreInfoDto.setScoreRaterEntityList(scoreRaterEntityList);

        return R.ok(scoreInfoDto);
    }



    @DeleteMapping("/deleteScore")
    @ApiOperation(value = "删除360评价信息")
    @Transactional
    public R deleteScore(@RequestParam(value = "id") String id){
        ScoreEntity scoreEntity=  scoreService.getByIdE(Long.valueOf(id));
        scoreRaterDao.delete(new QueryWrapper<ScoreRaterEntity>().eq("score_id",scoreEntity.getId()));
        scoreDao.deleteById(Long.valueOf(id));
        return  R.ok();
    }

    @PostMapping("updateScoreStatus")
    @ApiOperation(value = "修改360评价状态为评分中")
    @Transactional
    public R updateScoreStatus(@RequestParam(value = "id") String id){
        ScoreEntity scoreEntity=  scoreService.getByIdE(Long.valueOf(id));
        scoreEntity.setStatus(1);
        scoreService.updateByIdE(scoreEntity);

       List<ScoreRaterEntity> scoreRaterEntityList=  scoreRaterDao.selectList(new QueryWrapper<ScoreRaterEntity>().eq("score_id",scoreEntity.getId()));
        for (ScoreRaterEntity scoreRaterEntity:scoreRaterEntityList) {
            EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(scoreRaterEntity.getOid());
            EmployeeInfoEntity entity = employeeInfoService.getByIdE(scoreEntity.getOid());
            ScoreProgramEntity scoreProgramEntity = scoreProgramDao.selectById(scoreEntity.getProgramId());
            String title = "测评待办：请您对 " + entity.getName() + " 的 " + scoreProgramEntity.getProgramName() + " 进行360测评评分";
            String content = "请您登录员工自助系统对 " + entity.getName() + " 的 " + scoreProgramEntity.getProgramName() + " 进行360测评评分";
            qwMsg.sendNoticeMsg(title, title, NoticeConst.MSG_TYPE_SCORE, false, employeeInfoEntity.getOid(), scoreRaterEntity.getId(), "360测评评分", employeeInfoEntity.getCode(), null, null);
        }
        return R.ok();

    }

    @PostMapping("getScoreWeightsInfo")
    @ApiOperation(value = "获取360权重配置信息")
    public R getScoreWeightsInfo(@RequestParam(value = "id") String id){
        ScoreWeightsEntity scoreWeightsEntity=scoreWeightsService.getByIdE(Long.valueOf(id));
        return R.ok(scoreWeightsEntity);
    }

    @PostMapping("SaveAndUpdateScoreWeightsInfo")
    @ApiOperation(value = "保存或修改360权重配置信息")
    @Transactional
    public R getScoreWeightsInfo(@RequestBody @Valid ScoreWeightsVo scoreWeightsVo, HttpServletRequest request) throws Exception {
        JSONObject data =loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return  R.error("请先登录");
        }
        ScoreWeightsEntity scoreWeightsEntity = BeanUtilsMabach.doToDto(scoreWeightsVo, ScoreWeightsEntity.class);
        if(scoreWeightsVo.getId()==null){
            scoreWeightsEntity.setCreateCode(data.getString("usercode"));
            scoreWeightsEntity.setCreateName(data.getString("name"));
            scoreWeightsEntity.setCreateTime(new Date());
            scoreWeightsService.saveE(scoreWeightsEntity);
        }else {
            scoreWeightsService.updateByIdE(scoreWeightsEntity);
        }
        return R.ok(scoreWeightsEntity);
    }

    @PostMapping("saveScoreWeightsInfoAndScoreProgram")
    @ApiOperation(value = "新增方案信息和权重配置信息")
    @Transactional
    public R SaveScoreWeightsInfoAndScoreProgram(@RequestBody @Valid ScoreWeightsAndProgramVo scoreWeightsAndProgramVo, HttpServletRequest request) throws Exception {
        JSONObject data =loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return  R.error("请先登录");
        }
        ScoreWeightsEntity scoreWeightsEntity = BeanUtilsMabach.doToDto(scoreWeightsAndProgramVo, ScoreWeightsEntity.class);
        scoreWeightsEntity.setCreateTime(new Date());
        scoreWeightsEntity.setCreateName(data.getString("name"));
        scoreWeightsEntity.setCreateCode(data.getString("usercode"));
        scoreWeightsEntity.setIsDelete(0);
        scoreWeightsDao.insert(scoreWeightsEntity);

        ScoreProgramEntity scoreProgramEntity=new ScoreProgramEntity();
        scoreProgramEntity.setCreateCode(data.getString("usercode"));
        scoreProgramEntity.setCreateName(data.getString("name"));
        scoreProgramEntity.setCreateTime(new Date());
        scoreProgramEntity.setIsDelete(0);
        scoreProgramEntity.setProgramName(scoreWeightsAndProgramVo.getProgramName());
        scoreProgramEntity.setUnitId(data.getLong("depId"));
        scoreProgramEntity.setWeightsId(scoreWeightsEntity.getId());
        scoreProgramDao.insert(scoreProgramEntity);
        return R.ok();
    }


    @PostMapping("saveAndUpdateScoreTopicInfo")
    @ApiOperation(value = "保存或修改360题目信息")
    @Transactional
    public R SaveAndUpdateScoreTopicInfo(@RequestBody @Valid ScoreTopicVo scoreTopicVo, HttpServletRequest request) throws Exception {
        JSONObject data =loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return  R.error("请先登录");
        }
        ScoreTopicEntity scoreTopicEntity = BeanUtilsMabach.doToDto(scoreTopicVo, ScoreTopicEntity.class);
        if(scoreTopicVo.getId()==null){
            scoreTopicEntity.setCreateCode(data.getString("usercode"));
            scoreTopicEntity.setCreateName(data.getString("name"));
            scoreTopicEntity.setCreateTime(new Date());
            scoreTopicEntity.setIsDelete(0);
            scoreTopicDao.insert(scoreTopicEntity);
        }else {
            scoreTopicDao.updateById(scoreTopicEntity);
        }
        return R.ok(scoreTopicEntity.getId());
    }




    private JSONObject getRaterTopicScore(JSONObject jsonObject,List<ScoreTopicScoreDto> scoreTopicScoreDtos,int type,BigDecimal RoleWeights){
        BigDecimal score=jsonObject.getBigDecimal("score");
        BigDecimal weights=jsonObject.getBigDecimal("weights");
        List<ScoreTopicScoreDto> scoreDtoList=new ArrayList<>();
        for (ScoreTopicScoreDto scoreTopicScoreDto:scoreTopicScoreDtos){
            if(type==scoreTopicScoreDto.getType()){
                scoreDtoList.add(scoreTopicScoreDto);
            }
        }
        if(!CollectionUtils.isEmpty(scoreDtoList)){
            weights=  weights.add(RoleWeights);
        }
        for (ScoreTopicScoreDto scoreTopicScoreDto:scoreDtoList){
            BigDecimal weights1=RoleWeights.divide(new BigDecimal(scoreDtoList.size()),2, BigDecimal.ROUND_HALF_UP);
            score=score.add(scoreTopicScoreDto.getScore().multiply(weights1));
        }
        jsonObject.put("score",score);
        jsonObject.put("weights",weights);
        return jsonObject;
    }

    private JSONObject getScore(JSONObject jsonObject,Long scoreId,BigDecimal RoleWeights,Integer type){
        BigDecimal score=jsonObject.getBigDecimal("score");
        BigDecimal weights=jsonObject.getBigDecimal("weights");
        List<ScoreRaterEntity> scoreRater=scoreRaterDao.selectList(new QueryWrapper<ScoreRaterEntity>()
                .eq("score_id",scoreId)
                .eq("is_delete",0).eq("status",1).eq("type", type));
        if(!CollectionUtils.isEmpty(scoreRater)){
            weights=weights.add(RoleWeights);
        }
        for (ScoreRaterEntity scoreRaterEntity:scoreRater){
            BigDecimal weights1=RoleWeights.divide(new BigDecimal(scoreRater.size()),3, BigDecimal.ROUND_HALF_UP);
            score=score.add(scoreRaterEntity.getRaterScore().multiply(weights1));
        }
        jsonObject.put("score",score);
        jsonObject.put("weights",weights);
        return jsonObject;
    }

    public String getScoreNum(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = format.format(date);
        String nm = new SimpleDateFormat("yyyyMMdd").format(date);
        Long max = scoreDao.getScoreNum(datestr)+1;
        String employeeOidStr = String.format("%05d", max);
        return  nm+employeeOidStr;
    }


    public void saveScoreRater( Long scoreId,JSONObject userInfo, ArrayList<String> List, int type, Long weightsId){

        ScoreRaterEntity scoreRaterEntity=new ScoreRaterEntity();
        scoreRaterEntity.setCreateCode(userInfo.getString("usercode"));
        scoreRaterEntity.setCreateName(userInfo.getString("name"));
        scoreRaterEntity.setCreateTime(new Date());
        scoreRaterEntity.setStatus(0);
        scoreRaterEntity.setType(type);
        scoreRaterEntity.setScoreId(scoreId);
        ScoreWeightsEntity scoreWeightsEntity= scoreWeightsService.getByIdE(weightsId);
        for (String strOid:List) {
            scoreRaterEntity.setId(null);
            Long oid=Long.valueOf(strOid);
            EmployeeInfoEntity employeeInfoEntity=employeeInfoService.getByIdE(oid);
            scoreRaterEntity.setOid(oid);
            scoreRaterEntity.setUnitId(employeeInfoEntity.getUnitId());
            scoreRaterEntity.setName(employeeInfoEntity.getName());
            if (ScoreConst.SCORE_SUPERIOR_EIGHTS_TYPE == type) {
                BigDecimal weights=scoreWeightsEntity.getSuperiorWeights().divide(new BigDecimal(List.size()),4, BigDecimal.ROUND_HALF_UP);;
                scoreRaterEntity.setWeights(weights);
            } else if (ScoreConst.SCORE_SAME_LEVEL_EIGHTS_TYPE == type) {
                BigDecimal weights=scoreWeightsEntity.getSameLevelWeights().divide(new BigDecimal(List.size()),4, BigDecimal.ROUND_HALF_UP);;
                scoreRaterEntity.setWeights(weights);
            } else if (ScoreConst.SCORE_SUBORDINATE_EIGHTS_TYPE == type) {
                BigDecimal weights=scoreWeightsEntity.getSubordinateWeights().divide(new BigDecimal(List.size()),4, BigDecimal.ROUND_HALF_UP);;
                scoreRaterEntity.setWeights(weights);
            } else if (ScoreConst.SCORE_MY_EIGHTS_TYPE == type) {
                BigDecimal weights=scoreWeightsEntity.getMyWeights().divide(new BigDecimal(List.size()),4, BigDecimal.ROUND_HALF_UP);;
                scoreRaterEntity.setWeights(weights);
            }
            scoreRaterService.saveE(scoreRaterEntity);
        }
    }

}
